<template>
  <div class="pbx-migration__wrapper">
    <el-form :model="pbxForm" :rules="rules" ref="ruleForm" class = 'pbx-migration__form'>
    <div class='pbx-migration__top'>  
      <div class='pbx-migration__select'>
        <p>当前PBX</p>
        <el-input disabled v-model='PBX'></el-input>
      </div>
      <div class='pbx-migration__select'>
        <p>pbx机柜</p>
        <el-form-item  prop="INDEX_PBX">
        <el-select v-model="pbxForm.INDEX_PBX" placeholder="请选择" @change = 'pbxCabinetChange'  clearable filterable>
          <el-option
         v-for="item in pbxCabinet"
         :key="item._id"
         :label="item.name"
         :value="item.name">
           {{item.name}}
          </el-option>
        </el-select>
        </el-form-item>
      </div>
      <div class='pbx-migration__select'>
        <p>pbx机器</p>
        <div class='pbx-migration__select-box'>
          <div>
            <el-form-item  prop="PBX_NAME">
            <el-select v-model="pbxForm.PBX_NAME" clearable placeholder="请选择" @change = 'pbxMachineChange' filterable>
              <el-option
                v-for="item in pbxMachine"
                :key="item.allId"
                :label="item.name"
                :value="item.allId">
                {{item.name}}
              </el-option>
            </el-select>
            </el-form-item>
          </div>
          <span :class='pbxMachineType.type' v-show = 'pbxMachineType.type && pbxForm.PBX_NAME'>{{pbxMachineType.title}}</span>
        </div>
      </div>
      <div class='pbx-migration__select'>
        <p>pbx实例</p>
        <div class='pbx-migration__select-box'>
          <div>
            <el-form-item  prop="PBX">
            <el-select v-model="pbxForm.PBX" clearable placeholder="请选择" @change = 'pbxInstanceChange' filterable>
              <el-option
                v-for="item in pbxInstance"
                :key="item.allId"
                :label="item.num"
                :value="item.allId">
                {{item.num}}
              </el-option>
            </el-select>
            </el-form-item>
          </div>
          <span :class = 'pbxInstanceType.type' v-show = 'pbxInstanceType.type && pbxForm.PBX'>{{pbxInstanceType.title}}</span>
        </div>
      </div>
    </div>
    <div class='pbx-migration__tip'>
      <p>PBX机器与PBX实例的负载情况分4个级</p>
      <p><span class='success'>空闲</span><span class='warning'>繁忙</span><span class='important'>拥挤</span><span class='inverse'>饱和</span></p>
      <p>建议不要添加<span class='important'>拥挤</span>和<span class='inverse'>饱和</span>状态的PBX，这样可能会对通话产生影响</p>
    </div>
    <div class="pbx-migration__footer">
      <el-button class = 'slide-box__button' @click='cancelClick'>
        取消
      </el-button>
      <el-button class = 'slide-box__button' type="primary" @click='saveClick'>
        保存
      </el-button>
    </div>
    </el-form>
  </div>
</template>
<script>
  export default {
    name: 'pbxAdd',
    data () {
      return {
        name: 'pbxMigration',
        pbxIndexKeyMap: [],
        pbxNameMap: [],
        pbxCabinet: [],
        pbxMachine: [],
        pbxInstance: [],
        pbxMachineType: {
          type: '',
          title: ''
        },
        pbxInstanceType: {
          type: '',
          title: ''
        },
        rules: {
          INDEX_PBX: [
            {required: true, message: '请选择PBX机柜！', trigger: 'change'}
          ],
          PBX_NAME: [{
            required: true, trigger: 'change', message: '请选择PBX机器！'
          }],
          PBX: [{
            required: true, trigger: 'change', message: '请选择PBX实例！'
          }],
          NickName: [{
            required: true, trigger: 'change', message: '请填写昵称！'
          }]
        },
        pbxForm: {
          INDEX_PBX: '',
          PBX_NAME: '',
          PBX: '',
          NickName: ''
        }
      }
    },
    props: {
      pbxNickName: {
        type: String,
        default: ''
      },
      currentPBX: {
        type: String,
        default: ''
      }
    },
    computed: {
      PBX () {
        return this.pbxNickName + '(' + this.currentPBX + ')'
      }
    },
    mounted () {
      this.getAccountPbx()
    },
    methods: {
      getAccountPbx () {
        this.getAccountPbxBoard().then((data) => {
          this.$store.dispatch('getDicCache', {type: 'pbx'}).then((res) => {
            if (res.success) {
              let pbxList = res.data
              let endList = []
              let val = data
              let pbxNameMap = {}
              let pbxIndexKeyMap = {}
              let pbxKeyMap = {}
              let pbxIndexNameMap = []
              let ownPbxes = this.$store.state.session.account.pbx
              // ifEnableAdd 计费控制pbx是否开启
              let newList = pbxList.filter((item) => {
                return item.ifEnableAdd !== 1
              })
              if (ownPbxes) {
                for (let i = 0; i < newList.length; i++) {
                  let tag = false
                  for (var j = 0; j < ownPbxes.length; j++) {
                    if (ownPbxes[j].PBX === newList[i]._id || ownPbxes[j].PBX.substring(0, ownPbxes[j].PBX.lastIndexOf('.')) === newList[i]._id.substring(0, newList[i]._id.lastIndexOf('.'))) {
                      tag = true
                    }
                  }
                  if (!tag) {
                    endList.push(newList[i])
                  }
                }
              } else {
                endList = newList
              }
              for (var i = 0; i < endList.length; i++) {
                let currentId = endList[i]._id
                let currentName = endList[i].name
                let board = endList[i].board
                for (var k = 0; k < val.length; k++) {
                  if (board === val[k]._id) {
                    board = val[k].name
                  }
                }
                let pbxKey = currentId.substring(0, currentId.lastIndexOf('.'))
                let pbxInstance = currentId.substring(currentId.lastIndexOf('.') + 1)
                if (board in pbxIndexKeyMap) {
                  if (!(pbxKey in pbxKeyMap)) {
                    pbxIndexKeyMap[board].push({name: pbxKey, allId: pbxKey})
                    pbxKeyMap[pbxKey] = []
                    pbxKeyMap[pbxKey].push({name: currentName, allId: pbxKey})
                  }
                } else {
                  pbxIndexKeyMap[board] = []
                  pbxIndexKeyMap[board].push({name: pbxKey, allId: pbxKey})
                  pbxKeyMap[pbxKey] = []
                  pbxKeyMap[pbxKey].push({name: currentName, allId: pbxKey})
                }
                if (pbxKey in pbxNameMap) {
                  pbxNameMap[pbxKey].push({num: pbxInstance + '(' + currentName + ')', name: currentName, allId: currentId})
                } else {
                  pbxNameMap[pbxKey] = []
                  pbxNameMap[pbxKey].push({num: pbxInstance + '(' + currentName + ')', name: currentName, allId: currentId})
                }
              }
              this.pbxIndexKeyMap = pbxIndexKeyMap
              Object.keys(pbxIndexKeyMap).forEach((key) => {
                pbxIndexNameMap.push({name: key})
              })
              this.pbxNameMap = pbxNameMap
              this.pbxCabinet = pbxIndexNameMap
            }
          })
        })
      },
      getAccountPbxBoard () {
        return new Promise((resolve, reject) => {
          this.$store.dispatch('queryAccountPbxBoard', {idle: ''}).then((res) => {
            resolve(res.list)
          })
        })
      },
      pbxCabinetChange (val) {
        if (this.pbxIndexKeyMap && val) {
          this.pbxMachine = this.pbxIndexKeyMap[val]
        } else {
          this.pbxForm.INDEX_PBX = ''
          this.pbxMachine = []
          this.pbxInstance = []
        }
        this.pbxForm.PBX_NAME = ''
        this.pbxForm.PBX = ''
      },
      pbxMachineChange (val) {
        if (val) {
          this.pbxInstance = this.pbxNameMap[val]
          let currentPBX = val
          this.$store.dispatch('checkPbxMachineLoadInfo', {'pbxId': currentPBX}).then((state) => {
            this.pbxMachineType = state
          })
        } else {
          this.pbxInstance = []
        }
        this.pbxForm.PBX = ''
      },
      pbxInstanceChange (val) {
        let currentPBX = val
        this.$store.dispatch('checkPbxLoadInfo', {'pbxId': currentPBX}).then((state) => {
          this.pbxInstanceType = state
        })
      },
      saveClick () {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            // let Account = this.$store.state.session.account
            // let reqData = this.pbxForm
            this.$confirm('这是【迁移PBX】操作! 确定要执行吗？建议联系4001-113-114 让技术协助完成此动作!')
            .then(_ => {
              let lines = this.$store.state.session.ivrMap[this.currentPBX].data.ivr_line
              console.log(lines)
              for (let i = 0; i < lines.length; i++) {
                if (!lines[i].Exten && !lines[i].LineFlag) {
                  this.$confirm('您有[外呼]或[呼转]线路未配置，不能迁移。请先配置外呼和呼转线路后再迁移!')
                  return
                }
              }
              let query = {
                sipConfigName: this.currentPBX,
                oldsipConfigId: this.currentPBX,
                newsipConfigId: this.pbxForm.PBX,
                accountId: this.$store.state.session.account.account
              }
              console.log(query)
              this.$store.dispatch('moveAccountPbx', query).then((data) => {
                this.$message.success('迁移PBX成功，请稍等一会重新登录系统')
                this.cancelClick()
              })
            })
            .catch(_ => {
              return false
            })
          } else {
            return false
          }
        })
      },
      cancelClick () {
        this.$emit('taskComplete')
      }
    }
  }
</script>
<style lang="stylus" scoped>
.pbx-migration__wrapper
 height 100%
 .pbx-migration__form
  height 100%
  display flex
  flex-direction column
  .pbx-migration__top
   flex 1
   overflow-y auto
   padding 20px
   box-sizing border-box
  .pbx-migration__radio
    box-sizing border-box
    margin-bottom 20px
  .pbx-migration__select
    .pbx-migration__select-box
      display flex
      align-items center
      flex-direction row
      > div
       flex 1
      > span
       color white
       margin 0 10px 0
       padding 0px 4px 0px
       background #A5A5A5
      .success
        background #41B27F
      .warning
        background #FF9202
      .important
        background #FF6B6B
      .inverse  
        background #A5A5A5
    box-sizing border-box
    margin-bottom 20px
    .el-select
     width 100%
     box-sizing border-box
     margin-bottom 0px
    p
     font-size 14px
     font-family PingFangSC-Medium
     font-weight 500
     margin-bottom 6px
  .pbx-migration__tip
    height 133px
    width 100%
    padding 20px
    box-sizing border-box
    background rgba(246,246,246,1)
    color #3B5998
    p
     line-height 18px
     margin-bottom 10px
    span
     color white
     margin 0px 6px 0px
     padding 1px 3px 1px 
    .success
      margin-left 0px
      background #41B27F
    .warning
      background #FF9202
    .important
      background #FF6B6B
    .inverse  
      background #A5A5A5 
  .pbx-migration__footer
    background rgba(255,255,255,1)
    box-shadow 0px -2px 4px 0px rgba(5,49,38,0.05)
    border-top 1px solid rgba(232,232,232,1)
    display flex
    justify-content center
    padding 10px 0 10px
    box-sizing border-box
    .slide-box__button
      padding 8px 20px 8px
      box-sizing border-box
</style>
